package com.zihan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zihan.context.UserContext;
import com.zihan.domain.dto.AchievementDTO;
import com.zihan.domain.entity.Achievement;
import com.zihan.domain.entity.AchievementApproval;
import com.zihan.domain.entity.User;
import com.zihan.domain.result.PageResult;
import com.zihan.domain.result.Result;
import com.zihan.domain.vo.AchievementApprovalVO;
import com.zihan.domain.vo.AchievementVO;
import com.zihan.mapper.AchievementMapper;
import com.zihan.service.IAchievementApprovalService;
import com.zihan.service.IAchievementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zihan.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 成果表 服务实现类
 * </p>
 *
 * @author zhangzihan
 * @since 2025-10-17
 */
@Service
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements IAchievementService {

    @Resource
    private IAchievementApprovalService achievementApprovalService;
    @Resource
    private IUserService userService;

    /**
     * 添加成果
     */
    @Override
    public Result<String> addAchievement(Achievement achievement) {
        Long currentId = UserContext.getCurrentId();
        achievement.setUserId(currentId);
        save(achievement);
        return Result.success("添加成功");
    }


    /**
     * 获取当前学生成功
     * @param achievement
     * @return
     */
    @Override
    public Result<PageResult> getMyList(AchievementDTO achievement) {
        Long currentId = UserContext.getCurrentId();
        achievement.setUserId(currentId);
        Page<Achievement> page = new Page<>(achievement.getPageNo(), achievement.getPageSize());
        List<AchievementVO> res =baseMapper.getMyList(achievement,page);
        PageResult pageResult = new PageResult();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(res);
        return Result.success(pageResult);
    }


    /**
     * 获取成功详情
     * @param id
     * @return
     */
    @Override
    public Result<AchievementVO> getDetail(Long id) {
        // 获取基本信息
        Achievement achievement = lambdaQuery().eq(Achievement::getId, id).one();
        AchievementVO achievementVO = new AchievementVO();
        BeanUtil.copyProperties(achievement,achievementVO);

        // 查询用户基本信息
        Long userId = achievement.getUserId();
        User userInfo = userService.lambdaQuery().eq(User::getId, userId).one();
        achievementVO.setStudentName(userInfo.getUsername());
        achievementVO.setDepartment(userInfo.getDepartment());
        achievementVO.setAccount(userInfo.getAccount());
        achievementVO.setMajor(userInfo.getMajor());

        // 查询审核内容
        List<AchievementApproval> list = achievementApprovalService.lambdaQuery().eq(AchievementApproval::getAchievementId, id).list();
        List<AchievementApprovalVO> res = list.stream().map(item -> {
            AchievementApprovalVO achievementApprovalVO = new AchievementApprovalVO();
            BeanUtil.copyProperties(item, achievementApprovalVO);
            User user = userService.lambdaQuery().eq(User::getId, item.getApproverId()).one();
            achievementApprovalVO.setTeacherName(user.getUsername());
            return achievementApprovalVO;
        }).collect(Collectors.toList());

        achievementVO.setApprovals(res);
        return Result.success(achievementVO);
    }


    // 更新成果信息
    @Override
    public Result<String> updateAchievement(Achievement achievement) {
        // 获取id
        Long id = achievement.getId();
        // 判断是否通过了审核，如果通过了审核就不能修改
        AchievementApproval one = achievementApprovalService.lambdaQuery().eq(AchievementApproval::getAchievementId, id)
                .eq(AchievementApproval::getApprovalStatus, 1).one();
        if (one != null) {
            return Result.error("该成果已经通过审核，不能修改");
        }
        updateById(achievement);
        return Result.success("修改成功");
    }



    //删除成果信息
    @Transactional
    @Override
    public Result<String> deleteAchievement(Long id) {
        Achievement achievement = lambdaQuery().eq(Achievement::getId, id).one();
        removeById( achievement);

        //删除 成功审核表信息
        achievementApprovalService.remove(
                new LambdaQueryWrapper<>(AchievementApproval.class)
                        .eq(AchievementApproval::getAchievementId, id)
        );
        return Result.success("删除成功");
    }


    /**
     * 获取当前老师审核列表
     * @param achievement
     * @return
     */
    @Override
    public Result<PageResult> getTeacherReviewList(AchievementDTO achievement) {
        Long currentId = UserContext.getCurrentId();
        achievement.setUserId(currentId);
        Page<Achievement> page = new Page<>(achievement.getPageNo(), achievement.getPageSize());
        List<AchievementVO> res =baseMapper.getTeacherList(achievement,page);
        PageResult pageResult = new PageResult();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(res);
        return Result.success(pageResult);
    }


    /**
     * 教师审核
     * @param achievement
     * @return
     */
    @Transactional
    @Override
    public Result<String> teacherReview(Achievement achievement) {
        Long id = achievement.getId();
        Achievement one = lambdaQuery().eq(Achievement::getId, id).one();
        if (one == null) {
            return Result.error("该成果不存在");
        }
        if (one.getStatus() == 1) {
            return Result.error("该成果已经审核通过");
        }
        if (one.getStatus() == 2) {
            return Result.error("该成果已经审核未通过");
        }

        // 判断是添加拒绝还是同意
        Integer status = achievement.getStatus();
        AchievementApproval achievementApproval = new AchievementApproval();
        achievementApproval.setAchievementId(id);
        achievementApproval.setApproverId(UserContext.getCurrentId());
        achievementApproval.setComment(achievement.getComment());
        achievementApproval.setCreateTime(LocalDateTime.now());
        achievementApproval.setUpdateTime(LocalDateTime.now());
        if (status == 1) {
            // 通过审核
            one.setStatus(1);
            // 添加审核信息表
            achievementApproval.setApprovalType(1);
            achievementApproval.setApprovalStatus(1);
        }else  if (status == 2) {
            // 拒绝审核
            one.setStatus(2);
            // 添加审核信息表
            achievementApproval.setApprovalType(2);
            achievementApproval.setApprovalStatus(2);
        }
        //更新
        updateById(one);
        // 插入信息
        achievementApprovalService.save(achievementApproval);
        return Result.success("操作成功");
    }

    /**
     * 获取管理员审核列表
     * @param achievement
     * @return
     */
    @Override
    public Result<PageResult> getAdminReviewList(AchievementDTO achievement) {
        Long currentId = UserContext.getCurrentId();
        achievement.setUserId(currentId);
        Page<Achievement> page = new Page<>(achievement.getPageNo(), achievement.getPageSize());
        List<AchievementVO> res =baseMapper.getAdminList(achievement,page);
        // 设置初审老师id
        Set<Long> ids = res.stream().map(item -> {
            return item.getTeacherId();
        }).collect(Collectors.toSet());

        // 根据id获取老师
        if (!ids.isEmpty()) {
            List<User> list = userService.lambdaQuery().in(User::getId, ids).list();
            for (User user : list) {
                for (AchievementVO achievementVO : res) {
                    if (achievementVO.getTeacherId().equals(user.getId())) {
                        achievementVO.setTeacherName(user.getUsername());
                    }
                }
            }
        }

        PageResult pageResult = new PageResult();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(res);
        return Result.success(pageResult);
    }


    // 管理员审核
    @Override
    public Result<String> adminReview(Achievement achievement) {
        Long id = achievement.getId();
        Achievement one = lambdaQuery().eq(Achievement::getId, id).one();
        if (one == null) {
            return Result.error("该成果不存在");
        }
        if (one.getStatus() == 3) {
            return Result.error("该成果已经审核通过");
        }
        if (one.getStatus() == 4) {
            return Result.error("该成果已经审核未通过");
        }
        // 判断是添加拒绝还是同意
        Integer status = achievement.getStatus();
        AchievementApproval achievementApproval = new AchievementApproval();
        achievementApproval.setAchievementId(id);
        achievementApproval.setApproverId(UserContext.getCurrentId());
        achievementApproval.setComment(achievement.getComment());
        achievementApproval.setCreateTime(LocalDateTime.now());
        achievementApproval.setUpdateTime(LocalDateTime.now());
        if (status == 1) {
            // 通过审核
            one.setStatus(3);
            // 添加审核信息表
            achievementApproval.setApprovalType(1);
            achievementApproval.setApprovalStatus(1);
        }else  if (status == 2) {
            // 拒绝审核
            one.setStatus(4);
            // 添加审核信息表
            achievementApproval.setApprovalType(2);
            achievementApproval.setApprovalStatus(2);
        }
        //更新
        updateById(one);
        // 插入信息
        achievementApprovalService.save(achievementApproval);
        return Result.success("操作成功");
    }
}
